import { Toast } from "antd-mobile";
import store from "../../Store/Store";
import { InterfaceG } from "../../../config/Config";
import yhTools from "../../../tools/yh";

export const SET_SUPPORTED_BANK_LIST = "SET_SUPPORTED_BANK_LIST";

export const SET_MY_BANK_LIST = "SET_MY_BANK_LIST";

export const SET_USER_REAL_INFO = "SET_USER_REAL_INFO";

export const setSupportedBankList = data => ({
	type: SET_SUPPORTED_BANK_LIST,
	data
});

export const setMyBankList = data => ({
	type: SET_MY_BANK_LIST,
	data
});

export const setUserRealInfo = data => ({
	type: SET_USER_REAL_INFO,
	data
});

/**
 * 获取所有支持的银行
 */
export const getAllSupportedBankList = ({ channelCode }) => {
	Toast.loading("加载中...", 100);
	let obj = {
		url: InterfaceG.supportedBankcardList,
		params: {
			channelCode
		},
		_alertShow: false
	};
	return new Promise(resolve => {
		yhTools.request(obj).then(res => {
			if (res.code === "0") {
				Toast.hide();
				resolve(res.data);
			} else {
				Toast.info(res.message, 2);
			}
		});
	});
};

/**
 * 获取绑定银行卡详情
 */
export const getBankInfo = () => {
	return new Promise(resolve => {
		yhTools
			.request({
				url: InterfaceG.checkUserBankInfo,
				params: {},
				_alertShow: false
			})
			.then(res => {
				if (res.code === "0") {
					resolve(res.data);
				}
			});
	});
};

/**
 * 获取我的银行卡列表
 */
export const getAllMyBankList = () => {
	let obj = {
		url: InterfaceG.bankManageList,
		params: {
			channelCode: "ll"
		},
		_alertShow: false
	};
	return new Promise(resolve => {
		yhTools.request(obj).then(res => {
			if (res.code === "0") {
				resolve(res.data);
			} else {
				Toast.info(res.message, 2);
			}
		});
	});
};

export const getSupportedBankList = params => {
	return async dispatch => {
		const res = await getAllSupportedBankList(params);
		dispatch(setSupportedBankList(res));
	};
};

export const getMyBankList = params => {
	return async dispatch => {
		const res = await getAllMyBankList(params);
		dispatch(setMyBankList(res));
	};
};

export const getUserBankInfo = params => {
	return async dispatch => {
		dispatch(getSupportedBankList({ channelCode: params.channelCode }));
	};
};

/**
 * 银行卡查询实名
 */
export const checkBankRealName = () => {
	let _authHeaderStr = store.getState().getAppPlatformsDatas.authHeaderStr;
	let _userToken = JSON.parse(_authHeaderStr).userToken;
	return new Promise(resolve => {
		yhTools
			.request({
				url: InterfaceG.checkBankRealName,
				params: {
					userToken: _userToken
				},
				_alertShow: false
			})
			.then(res => {
				resolve(res);
			});
	});
};
export const getUserRealInfo = () => {
	return async dispatch => {
		const res = await checkBankRealName();
		if (res.code === "0") {
			let info = {
				userName: res.data.certName,
				userRealNo: res.data.certNo
			};
			dispatch(setUserRealInfo(info));
		}
		dispatch(getSupportedBankList({ channelCode: "ll" }));
	};
};
